package db

import (
	"database/sql"
	"fmt"
	"k8s-service/models"
	"log"
	"time"

	_ "modernc.org/sqlite"
)

type ModelConfigDB struct {
	db *sql.DB
}

// NewModelConfigDB 创建ModelConfigDB实例
func NewModelConfigDB(dbPath string) (*ModelConfigDB, error) {
	db, err := sql.Open("sqlite", dbPath)
	if err != nil {
		return nil, fmt.Errorf("无法打开数据库: %v", err)
	}

	// 测试数据库连接
	if err := db.Ping(); err != nil {
		return nil, fmt.Errorf("数据库连接测试失败: %v", err)
	}

	// 初始化数据库表
	if err := initializeDatabase(db); err != nil {
		return nil, fmt.Errorf("数据库初始化失败: %v", err)
	}

	return &ModelConfigDB{db: db}, nil
}

// initializeDatabase 初始化数据库表
func initializeDatabase(db *sql.DB) error {
	createTableSQL := `
	CREATE TABLE IF NOT EXISTS model_config (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		model_path TEXT NOT NULL,
		request_headers TEXT,
		vendor_cn TEXT NOT NULL,
		vendor_en TEXT,
		vendor_img TEXT,
		model_name TEXT,
		model_type TEXT NOT NULL,
		enabled INTEGER DEFAULT 1,
		created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
		updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
	);
	`

	_, err := db.Exec(createTableSQL)
	if err != nil {
		return fmt.Errorf("创建 model_config 表失败: %v", err)
	}

	log.Println("数据库表初始化成功")
	return nil
}

// Close 关闭数据库连接
func (mdb *ModelConfigDB) Close() error {
	return mdb.db.Close()
}

// CreateModelConfig 创建模型配置
func (mdb *ModelConfigDB) CreateModelConfig(config *models.ModelConfig) error {
	query := `
		INSERT INTO model_config (model_path, request_headers, vendor_cn, vendor_en, vendor_img, model_name, model_type, enabled)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?)
	`

	now := time.Now()
	config.CreatedAt = now
	config.UpdatedAt = now

	result, err := mdb.db.Exec(query,
		config.ModelPath,
		config.RequestHeaders,
		config.VendorCN,
		config.VendorEN,
		config.VendorImg,
		config.ModelName,
		config.ModelType,
		config.Enabled,
	)

	if err != nil {
		return fmt.Errorf("创建模型配置失败: %v", err)
	}

	// 获取插入的ID
	id, err := result.LastInsertId()
	if err != nil {
		return fmt.Errorf("获取插入ID失败: %v", err)
	}

	config.ID = int(id)
	log.Printf("成功创建模型配置，ID: %d", config.ID)
	return nil
}

// GetModelConfigByID 根据ID获取模型配置
func (mdb *ModelConfigDB) GetModelConfigByID(id int) (*models.ModelConfig, error) {
	query := `
		SELECT id, model_path, request_headers, vendor_cn, vendor_en, vendor_img, model_name, model_type, enabled
		FROM model_config
		WHERE id = ?
	`

	var config models.ModelConfig
	var vendorImg, modelName sql.NullString

	err := mdb.db.QueryRow(query, id).Scan(
		&config.ID,
		&config.ModelPath,
		&config.RequestHeaders,
		&config.VendorCN,
		&config.VendorEN,
		&vendorImg,
		&modelName,
		&config.ModelType,
		&config.Enabled,
	)

	if err != nil {
		if err == sql.ErrNoRows {
			return nil, fmt.Errorf("模型配置不存在")
		}
		return nil, fmt.Errorf("查询模型配置失败: %v", err)
	}

	// 处理可能为NULL的字段
	if vendorImg.Valid {
		config.VendorImg = &vendorImg.String
	}
	if modelName.Valid {
		config.ModelName = &modelName.String
	}

	// 设置默认时间
	now := time.Now()
	config.CreatedAt = now
	config.UpdatedAt = now

	return &config, nil
}

// UpdateModelConfig 更新模型配置
func (mdb *ModelConfigDB) UpdateModelConfig(id int, config *models.ModelConfig) error {
	// 先检查记录是否存在
	if _, err := mdb.GetModelConfigByID(id); err != nil {
		return err
	}

	query := `
		UPDATE model_config 
		SET model_path = ?, request_headers = ?, vendor_cn = ?, vendor_en = ?, 
		    vendor_img = ?, model_name = ?, model_type = ?, enabled = ?
		WHERE id = ?
	`

	config.UpdatedAt = time.Now()

	_, err := mdb.db.Exec(query,
		config.ModelPath,
		config.RequestHeaders,
		config.VendorCN,
		config.VendorEN,
		config.VendorImg,
		config.ModelName,
		config.ModelType,
		config.Enabled,
		id,
	)

	if err != nil {
		return fmt.Errorf("更新模型配置失败: %v", err)
	}

	config.ID = id
	log.Printf("成功更新模型配置，ID: %d", id)
	return nil
}

// DeleteModelConfig 删除模型配置
func (mdb *ModelConfigDB) DeleteModelConfig(id int) error {
	// 先检查记录是否存在
	if _, err := mdb.GetModelConfigByID(id); err != nil {
		return err
	}

	query := `DELETE FROM model_config WHERE id = ?`

	_, err := mdb.db.Exec(query, id)
	if err != nil {
		return fmt.Errorf("删除模型配置失败: %v", err)
	}

	log.Printf("成功删除模型配置，ID: %d", id)
	return nil
}

// ListModelConfigs 获取模型配置列表
func (mdb *ModelConfigDB) ListModelConfigs(page, size int, modelType string, enabled *int) ([]models.ModelConfig, int, error) {
	// 构建查询条件
	whereClause := "WHERE 1=1"
	args := []interface{}{}

	if modelType != "" {
		whereClause += " AND model_type = ?"
		args = append(args, modelType)
	}

	if enabled != nil {
		whereClause += " AND enabled = ?"
		args = append(args, *enabled)
	}

	// 获取总数
	countQuery := fmt.Sprintf("SELECT COUNT(*) FROM model_config %s", whereClause)
	var total int
	err := mdb.db.QueryRow(countQuery, args...).Scan(&total)
	if err != nil {
		return nil, 0, fmt.Errorf("查询总数失败: %v", err)
	}

	// 获取分页数据
	offset := (page - 1) * size
	dataQuery := fmt.Sprintf(`
		SELECT id, model_path, request_headers, vendor_cn, vendor_en, vendor_img, model_name, model_type, enabled
		FROM model_config %s
		ORDER BY id DESC
		LIMIT ? OFFSET ?
	`, whereClause)

	args = append(args, size, offset)

	rows, err := mdb.db.Query(dataQuery, args...)
	if err != nil {
		return nil, 0, fmt.Errorf("查询模型配置列表失败: %v", err)
	}
	defer rows.Close()

	var configs []models.ModelConfig
	for rows.Next() {
		var config models.ModelConfig
		var vendorImg, modelName sql.NullString

		err := rows.Scan(
			&config.ID,
			&config.ModelPath,
			&config.RequestHeaders,
			&config.VendorCN,
			&config.VendorEN,
			&vendorImg,
			&modelName,
			&config.ModelType,
			&config.Enabled,
		)

		if err != nil {
			return nil, 0, fmt.Errorf("扫描行数据失败: %v", err)
		}

		// 处理可能为NULL的字段
		if vendorImg.Valid {
			config.VendorImg = &vendorImg.String
		}
		if modelName.Valid {
			config.ModelName = &modelName.String
		}

		// 设置默认时间
		now := time.Now()
		config.CreatedAt = now
		config.UpdatedAt = now

		configs = append(configs, config)
	}

	if err = rows.Err(); err != nil {
		return nil, 0, fmt.Errorf("遍历行数据失败: %v", err)
	}

	return configs, total, nil
}

// GetEnabledModelConfigs 获取所有启用的模型配置
func (mdb *ModelConfigDB) GetEnabledModelConfigs() ([]models.ModelConfig, error) {
	configs, _, err := mdb.ListModelConfigs(1, 1000, "", &[]int{1}[0])
	return configs, err
}
